package org.geemp.game.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author JackRen
 * @date 2021-12-01 14:15
 * @description:
 */

@Configuration//注册到springboot容器
@MapperScan(basePackages= {"org.geemp.game.chart"},sqlSessionFactoryRef="chartSqlSessionFactory")
public class DateSourceChartConfig {

    @Bean(name="chartDataSource")//注入到这个容器
    @ConfigurationProperties(prefix="spring.datasource.chart")//表示取application.properties配置文件中的前缀
    public DataSource chartDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name="chartSqlSessionFactory")
    public SqlSessionFactory chartSqlSessionFactory(@Qualifier("chartDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }
    @Bean(name="chartTransactionManager")//配置事务
    public DataSourceTransactionManager chartTransactionManager(@Qualifier("chartDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean(name="chartSqlSessionTemplate")
    public SqlSessionTemplate chartSqlSessionTemplate(@Qualifier("chartSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
